import React, { act, useEffect, useState } from 'react';
import {
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormRadio,
  ProFormTextArea,
  ProFormSelect,
  ProFormDateTimePicker
} from '@ant-design/pro-components';
import { Form, message, Modal, Progress, Slider } from 'antd';
import { useIntl, FormattedMessage, useModel,useAccess} from '@umijs/max';
import { getAssetList,getdeviceNames ,getDeviceNumsByName} from '@/services/manage/asset';
import { getTaskList } from '@/services/manage/task';
import {getRouteNames} from '@/services/manage/route';


export type InspectionFormData = Record<string, unknown> & Partial<API.Manage.Inspection>;

export type InspectionFormProps = {
  onCancel: (flag?: boolean, formVals?: InspectionFormData) => void;
  onSubmit: (values: InspectionFormData) => Promise<void>;
  open: boolean;
}

const InspectionForm: React.FC<InspectionFormProps> = (props) => {
  const {onCancel, onSubmit, open} = props;
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser; 
  const [deviceNums, setDeviceNums] = useState<string[]>([]);
  const [deviceNames, setDeviceNames] = useState<string[]>([]);
  const [routeNames, setRouteNames] = useState<string[]>([]);
  const access = useAccess();
  
 //获取设备名称
   const allDeviceNames = async () =>{
     try{
       if(access.hasPerms('inspection:asset:allDeviceName')){
         const deviceNames = await getdeviceNames();
         const deviceNameList = Array.isArray(deviceNames?.rows) ? deviceNames.rows : [];
         setDeviceNames(deviceNameList);
       }
     }
     catch(error){
       message.error('获取设备名称失败:');
       setDeviceNames([]);
     }
   }

   const allRouteNames = async () =>{
     try{
      if(access.hasPerms('inspection:patrolRoute:allName')){
        const routeNames = await getRouteNames();
        const routeNameList = Array.isArray(routeNames?.data) ? routeNames.data : [];
        setRouteNames(routeNameList);
      }
    }catch(error){
      message.error('获取路线名称失败:');
      setRouteNames([]);
    }
  }

  useEffect(() => {
    form.resetFields();
  }, [form, props]);

  useEffect(() => {
    allDeviceNames();
    allRouteNames();
  }, []);


  const handleFinish = async (values: Record<string, any>) => {

    const InspectionFormData = {
      ...values,
      taskStatus: 0, // 默认未完成
      initiator: currentUser?.nickName, // 发起人
      actualStart: '', // 实际开始时间
      actualEnd: '', // 实际结束时间
    }
    console.log(InspectionFormData);
    onSubmit(InspectionFormData); // 提交表单数据
  };

  return (
    <Modal
      width={640}
      title='添加巡检'
      forceRender
      open={open}
      onOk={()=>form.submit()} // 触发表单提交
      onCancel={()=>onCancel()} // 关闭模态框
    >
      <ProForm
        form={form}
        grid={true}
        layout="horizontal"
        submitter={false}
        onFinish={handleFinish} // 处理表单提交
        initialValues={{
          date: Date.now(),
          time: Date.now(),
        }}
        >
        <ProFormText
          name="taskName"
          label='任务名称'
          placeholder="请输入任务名称"
          rules={[
            {
              required: true,
              message: "请输入任务名称!",
            },
          ]}
        />
        <ProFormRadio.Group
          name="taskType"
          options={[
            { label: '临时', value: '临时' },
            { label: '例行', value: '例行' },
          ]}
          label='任务类型'
          placeholder="请选择任务类型"
          rules={[
            {
              required: true,
              message:"请选择任务类型",
            },
          ]}
        /> 
        <ProFormSelect
          name="deviceName"
          label='设备名称'
          options={deviceNames}
          placeholder="请选择设备名称"
          
          rules={[{ required: true, message: '请选择设备名称!' }]}
          onChange={async (value: string | undefined) => {
            if (value && access.hasPerms('inspection:asset:deviceNums')) {
              const deviceNum = await getDeviceNumsByName(value);
              setDeviceNums(deviceNum?.rows);
            } else {
              // 清空设备编号选项和字段值
              setDeviceNums([]);
              form.setFieldsValue({ deviceNum: undefined });
            }
        }}
        />
        <ProFormSelect
          name="deviceNum"
          label='设备编号'
          placeholder="请选择设备编号"
          options={deviceNums}
          rules={[
            {
              required: true,
              message: "请选择设备编号!",
            },           
          ]}
        />
        <ProFormSelect
          name="routeName"
          label='路线名称'
          options={routeNames}
          placeholder="请选择路线名称"
          rules={[
            {
              required: true,
              message: "请选择路线名称!",
            },
          ]}      
        />    
        <ProFormDateTimePicker
          name="planStart"
          label="计划开始时间"
          fieldProps={{
            format: 'YYYY-MM-DD HH:mm:ss',  // 可自定义时间格式
            showTime: true,
          }}
          rules={[
            {
              required: true,
              message: "请选择计划开始时间！",
            },
          ]}
        /> 
        <ProFormDateTimePicker
          name="planEnd"
          label="计划结束时间"
          fieldProps={{
            format: 'YYYY-MM-DD HH:mm:ss',  // 可自定义时间格式
            showTime: true,
          }}
          rules={[
            {
              required: true,
              message: "请选择计划结束时间！",
            },
          ]}
        />

        
      </ProForm>
    </Modal>
  );
};

export default InspectionForm;